<?php

namespace Taxx\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Taxx\UserBundle\Forms\RegisterForm;
use Taxx\UserBundle\FormValidators\RegisterFormValidator;
use Taxx\UserBundle\Forms\LoginForm;
use Taxx\UserBundle\Forms\ForgotPasswordForm;
use Taxx\KernelBundle\Entity\User;
use Taxx\KernelBundle\Model\Utils\JsonTranslator;
use Taxx\KernelBundle\Model\Utils\PublicFileRegistry;
use Taxx\KernelBundle\Model\Utils\PasswordUtils;
use Symfony\Component\HttpFoundation\Session;

class LandingpageController extends Controller
{
    
    public function indexAction()
    {        
        /*
         * @TAXX_TODO: Create form to choose language 
         */
        
        if(!$this->getRequest()->request->has('selected_language'))
            $language = 'english';
        else
            $language = $this->getRequest()->request->get('selected_language');
        
        $this->getRequest()->getSession()->set('language', $language);
        
        $login_form = new LoginForm($language);
        $forgot_password_form = new ForgotPasswordForm($language);
        $register_form = new RegisterForm($this->get('doctrine.orm.entity_manager'), $language);
        return $this->render('TaxxUserBundle:Landingpage:index.html.twig', 
                            array(
                                    'login_form'=>$login_form->getForm($this->get('router')->generate('user_login')),
                                    'forgot_password_form'=>$forgot_password_form->getForm($this->get('router')->generate('user_forgot_password')),
                                    'register_form'=>$register_form->getForm($this->get('router')->generate('user_register')),
                                )
                            );
    }
    
    public function loginAction()
    {
        $language = $this->getRequest()->getSession()->get('language');
        
        $session  = $this->get("session");
        $em = $this->get('doctrine.orm.entity_manager');
        $translations = JsonTranslator::parseTranslationFile(PublicFileRegistry::getFilePath('user_translations'));
        
        $user = $em->getRepository('TaxxKernelBundle:User')->findOneBy(array("username" => $_POST['username']));
        
        if($user==null)
            $session->setFlash('error', $translations['messages'][$language]['wrong_username_password']);
        else
        {
            $saved_encrypted_password = $user->getPassword();
            $saved_salt = $user->getSalt();
            $verfied = PasswordUtils::verifyPassword($_POST['password'], $saved_salt, $saved_encrypted_password);
            
            if($verfied && $user->getActive()=='1')
            {
                $session->set("language", $user->getLanguage());
                $session->set("user_id", $user->getId());
                $session->set("password", $user->getPassword());
                return new RedirectResponse($this->get('router')->generate('board_index'));
            }
            else if($verfied && $user->getActive()!='1')
                $session->setFlash('error', $translations['messages'][$language]['user_not_active']);
            else
                $session->setFlash('error', $translations['messages'][$language]['wrong_username_password']);
        }
        
        return new RedirectResponse($this->get('router')->generate('landingpage'));
    }
    
    public function forgotPasswordAction()
    {
        $language = $this->getRequest()->getSession()->get('language');
        
        $translations = JsonTranslator::parseTranslationFile(PublicFileRegistry::getFilePath('user_translations'));
        
        $em = $this->get('doctrine.orm.entity_manager');
        if($_POST['email']!="")
            $user = $em->getRepository('TaxxKernelBundle:User')->findOneBy(array("email" => $_POST['email']));
        else if($_POST['username']!="")
            $user = $em->getRepository('TaxxKernelBundle:User')->findOneBy(array("username" => $_POST['username']));
        
        if($user==null)
            $this->get("session")->setFlash('error', $translations['messages'][$language]['user_not_found']);
        else
        {
            $new_raw_password = PasswordUtils::generateRawPassword();
            $encrypted_new_password = PasswordUtils::generatePassword($new_raw_password, $user->getSalt());
            $user->setPassword($encrypted_new_password);
            $em->persist($user);
            $em->flush();
            
            $subject = $translations['mail']['forgot_password_mail'][$language]['subject'];
            $msg_txt = $translations['mail']['forgot_password_mail'][$language]['message'];
            $msg_txt = str_replace("%username%", $user->getUsername(), $msg_txt);
            $msg_txt = str_replace("%password%", $new_raw_password, $msg_txt);
            
            $message = \Swift_Message::newInstance()
            ->setSubject($subject)
            ->setFrom('taxx.social.learning@googlemail.com')
            ->setTo($user->getEmail())
            ->setBody($msg_txt)
            ;
            $this->get('mailer')->send($message);
            
            $this->get("session")->setFlash('notice', $translations['messages'][$language]['forgot_password_mail_sent']);
        }
        
        return new RedirectResponse($this->get('router')->generate('landingpage'));
    }
    
    public function registerAction()
    {
        $language = $this->getRequest()->getSession()->get('language');
        $translations = JsonTranslator::parseTranslationFile(PublicFileRegistry::getFilePath('user_translations'));
        
        $em = $this->get('doctrine.orm.entity_manager');
        $validator = new RegisterFormValidator($em, $_POST);
        $validation = $validator->validate();
        
        if($validation['error'])
        {
            $this->get("session")->setFlash('error', $translations['messages'][$language]['registration_fail']);
            return new RedirectResponse($this->get('router')->generate('landingpage'));
        }
        else
        {
            $user = new User($_POST, $em);
            $em->persist($user);
            $em->flush();
            
            /*send registration mail*/
            $subject = $translations['mail']['registration_mail'][$language]['subject'];
            $msg_txt = $translations['mail']['registration_mail'][$language]['message'];
            $msg_txt = str_replace("%username%", $_POST['username'], $msg_txt);
            $msg_txt = str_replace("%password%", $_POST['password'], $msg_txt);
            $msg_txt = str_replace("%activation_link%", "http://taxx.test".$this->get('router')->generate('confirm_registration', array('code'=>$user->getConfirmationCode())), $msg_txt);
            
            $message = \Swift_Message::newInstance()
            ->setSubject($subject)
            ->setFrom('taxx.social.learning@googlemail.com')
            ->setTo($_POST['email'])
            ->setBody($msg_txt)
            ;
            $this->get('mailer')->send($message);
            
            $this->get("session")->setFlash('notice', $translations['messages'][$language]['registration_success']);
        }

        return new RedirectResponse($this->get('router')->generate('landingpage'));
    }
    
    public function confirmRegistrationAction($code)
    {
        $language = $this->getRequest()->getSession()->get('language');
        
        $translations = JsonTranslator::parseTranslationFile(PublicFileRegistry::getFilePath('user_translations'));
        
        $em = $this->get('doctrine.orm.entity_manager');
        $user = $em->getRepository("TaxxKernelBundle:User")->findOneBy(array('confirmation_code'=>$code));
        if(count($user)>0)
        {
            if($user->getActive()=="1")
                $this->get("session")->setFlash('notice', $translations['messages'][$language]['account_already_activated']);
            else
            {
                $user->setActive(1);
                $em->persist($user);
                $em->flush();
                $this->get("session")->setFlash('notice', $translations['messages'][$language]['account_activation_success']);
            }
        }
        else
            $this->get("session")->setFlash('error', $translations['messages'][$language]['account_activation_failure']);
        
        return new RedirectResponse($this->get('router')->generate('landingpage'));
    }
}
